<template>
    <div class="move-obj" :style="baseStyle" @animationend="animationend">
        <label v-if="title" class="title">{{title}}</label>
        <img v-if="image" :src="image" class="image" :style="imageStyle">
        <slot></slot>
    </div>
</template>

<script>
    export default {
        props:{
            name:{
                type:String,
                required:true
            },
            startPos:{ //起始位置
                type:String,
                default:'0px,0px'
            },
            offsetPos:String, //偏移位置
            interval:{ //时长 单位秒
                type:Number,
                default:3
            },
            infinite:{ //是否循环
                type:Boolean,
                default:true
            },
            image:String,
            title:String,
        },
        data(){
            return {
                baseStyle:{},
                imageStyle:{},
                isBack : true
            }
        },
        methods:{
            animationend(){
                if(this.infinite){
                    this.baseStyle.animationName = this.isBack? `${this.name}_back`:this.name
                    this.imageStyle.transform = this.isBack? 'rotateY(180deg)':'rotateY(0deg)'
                    this.isBack = !this.isBack;
                }
            }
        },
        created(){
            this.baseStyle = {
                left:this.startPos.split(',')[0],
                top:this.startPos.split(',')[1]
            }
            if(this.offsetPos){
                let style = document.styleSheets[0]
                style.insertRule(`@keyframes ${this.name} { 0%{transform:translate(0,0);}  100%{transform:translate(${this.offsetPos})} }`)
                style.insertRule(`@keyframes ${this.name}_back { 0%{transform:translate(${this.offsetPos});}  100%{transform:translate(0,0)}  }`)
                this.baseStyle.animationName = this.name
                this.baseStyle.animationDuration = `${this.interval}s`
                this.baseStyle.animationTimingFunction = this.name
                this.baseStyle = {
                    animationName: this.name,
                    animationDuration:`${this.interval}s`,
                    animationTimingFunction: 'linear',
                    left:this.startPos.split(',')[0],
                    top:this.startPos.split(',')[1]
                }
            }
        }
    }
</script>

<style scoped lang="scss">
.move-obj{
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    animation-fill-mode:both;
    animation-delay:0.1s;
    .title{
        font-size: 38px;
        color:#333333;
        margin-bottom: 20px;
        font-weight: bold;
    }
    .image{
        cursor: pointer;
    }
}
</style>